/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.oim.test.tcp;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.oim.test.tcp.client.NetConnector;
import com.oim.test.tcp.server.Server;
import com.onlyxiahui.net.connect.ConnectData;

/**
 *
 * @author Only
 */
public class ClientFrame extends javax.swing.JFrame {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    /**
     * Creates new form ClientFrame
     */

    NetConnector nc;

    NetConnector nnc;
    Server server = new Server();

    int port = 0;

    public ClientFrame() {
        initComponents();
        initNet();
    }

    private void initNet() {
        nc = new NetConnector(new IoHandlerAdapter() {
            public void sessionCreated(IoSession session) throws Exception {
            }

            public void sessionOpened(IoSession session) throws Exception {
                System.out.println("getRemoteAddress:" + session.getRemoteAddress());
                System.out.println("getLocalAddress:" + session.getLocalAddress());
                System.out.println("getServiceAddress:" + session.getServiceAddress());
                SocketAddress socketAddress = session.getLocalAddress();
                nc.closeConnect();
                if (socketAddress instanceof InetSocketAddress) {
                    InetSocketAddress isa = (InetSocketAddress) socketAddress;
                    port = isa.getPort();
                    server.startServer(port);
                }
            }

            public void sessionClosed(IoSession session) throws Exception {
            }

            public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            }

            public void messageReceived(IoSession session, Object message) throws Exception {
            }

            public void messageSent(IoSession session, Object message) throws Exception {
            }

            public void inputClosed(IoSession session) throws Exception {
                session.closeNow();
            }
        });
        ConnectData connectData = new ConnectData();
        connectData.setAddress("192.168.10.100");
        connectData.setPort(13000);
        nc.connect(connectData);

        nnc = new NetConnector(new IoHandlerAdapter() {
            public void sessionCreated(IoSession session) throws Exception {
            }

            public void sessionOpened(IoSession session) throws Exception {
                System.out.println("getRemoteAddress:" + session.getRemoteAddress());
                System.out.println("getLocalAddress:" + session.getLocalAddress());
                System.out.println("getServiceAddress:" + session.getServiceAddress());
            }

            public void sessionClosed(IoSession session) throws Exception {
            }

            public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
            }

            public void messageReceived(IoSession session, Object message) throws Exception {
            }

            public void messageSent(IoSession session, Object message) throws Exception {
            }

            public void inputClosed(IoSession session) throws Exception {
                session.closeNow();
            }
        });
        //nnc.setDefaultPort(nc.getPort());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated
    // <editor-fold defaultstate="collapsed" desc="Generated
	// Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		netButton = new javax.swing.JButton();
		sendButton = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		textArea = new javax.swing.JTextArea();
		portField = new javax.swing.JTextField();
		ip4Field = new javax.swing.JTextField();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		netButton.setText("连接");
		netButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				netButtonActionPerformed(evt);
			}
		});

		sendButton.setText("发送");
		sendButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				sendButtonActionPerformed(evt);
			}
		});

		textArea.setColumns(20);
		textArea.setRows(5);
		jScrollPane1.setViewportView(textArea);

		portField.setText("onlyNumberField1");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(layout.createSequentialGroup()
								.addGap(24, 24, 24)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addGroup(layout.createSequentialGroup()
												.addComponent(ip4Field, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
												.addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addGap(10, 10, 10)
												.addComponent(netButton)
												.addGap(32, 32, 32))
										.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
												.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 308, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addGap(18, 18, 18)
												.addComponent(sendButton)
												.addContainerGap(33, Short.MAX_VALUE)))));
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
								.addGap(32, 32, 32)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(netButton)
										.addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
										.addComponent(ip4Field, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
										.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
										.addComponent(sendButton, javax.swing.GroupLayout.Alignment.TRAILING))
								.addGap(24, 24, 24)));

		pack();
	}// </editor-fold>//GEN-END:initComponents

    private void netButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_netButtonActionPerformed
        net();
    }// GEN-LAST:event_netButtonActionPerformed

    private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_sendButtonActionPerformed
        send();
    }// GEN-LAST:event_sendButtonActionPerformed

    private void net() {
        //nnc.setDefaultPort(port);
//        String ip = this.ip4Field.getIpAddress();
//        int port = this.portField.getNumber().intValue();
//        ConnectData connectData = new ConnectData();
//        connectData.setAddress(ip);
//        connectData.setPort(port);
//        nnc.connect(connectData);
    }

    private void send() {
        String text = this.textArea.getText();
        nnc.write(text);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        // <editor-fold defaultstate="collapsed" desc=" Look and feel setting
        // code (optional) ">
        /*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.
		 * html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ClientFrame().setVisible(true);
            }
        });
    }

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JTextField ip4Field;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JButton netButton;
	private javax.swing.JTextField portField;
	private javax.swing.JButton sendButton;
	private javax.swing.JTextArea textArea;
	// End of variables declaration//GEN-END:variables
}
